<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>正在租用</title>
  <link rel="stylesheet" href="../plugins/elementui/index.css">
  <script src="../js/vue.js"></script>
  <script src="../plugins/elementui/index.js"></script>
  <link rel="stylesheet" href="css/webbase.css">
  <style>
    .rental-container {
      max-width: 1000px;
      margin: 20px auto;
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .rental-header {
      text-align: center;
      font-size: 26px;
      font-weight: bold;
      color: #333;
      margin-bottom: 30px;
    }

    .game-card {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      padding: 20px;
      background-color: #f9fafc;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    .game-card img {
      width: 110px;
      height: 150px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    .game-info {
      flex-grow: 1;
      margin-left: 20px;
    }

    .game-info h3 {
      font-size: 22px;
      font-weight: bold;
      color: #333;
      margin: 0;
      margin-bottom: 10px;
    }

    .game-info p {
      margin: 5px 0;
      font-size: 16px;
      color: #555;
    }

    .account-info {
      margin-right: 120px;
      width: 150px;
    }

    .account-info p {
      margin: 5px 0;
      font-size: 16px;
      color: #666;
    }

    .account-info .text-danger {
      color: #f56c6c;
      font-weight: bold;
    }

    .action-buttons {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    .action-buttons .el-button {
      margin-bottom: 10px;
    }

    .empty-text {
      text-align: center;
      color: #909399;
      font-size: 18px;
      margin-top: 50px;
    }

    .text-danger {
      color: #f56c6c;
      font-weight: bold;
      animation: blink 1s infinite;
    }

    @keyframes blink {
      0% {
        opacity: 1;
      }

      50% {
        opacity: 0.5;
      }

      100% {
        opacity: 1;
      }
    }

    .el-button+.el-button,
    .el-checkbox.is-bordered+.el-checkbox.is-bordered {
      margin-left: 0px
    }
  </style>
</head>

<body>
  <div id="app">
    <app-header></app-header>
    <div class="rental-container">
      <h2 class="rental-header">正在租用</h2>
      <div v-for="rental in rentals" :key="rental.id" class="game-card">
        <img :src="rental.imageUrl" alt="游戏图片">
        <div class="game-info">
          <h3>{{ rental.name }}</h3>
          <p>账号编号: {{ rental.gameId }}</p>
          <p>剩余时间: <span class="text-danger">{{ calculateRemainingTime(rental.endTime) }}</span></p>
        </div>
        <div class="account-info">
          <p @click="copyToClipboard(rental.account)">账号: {{ rental.account }}</p>
          <p @click="copyToClipboard(rental.password)">密码: {{ rental.password }}</p>
          <p><el-button type="danger" size="small" @click="getVerifi(rental)">获取令牌</el-button> </p>
          <p @click="copyToClipboard(rental.verificationCode)" style="cursor: pointer;">验证码: {{ rental.verificationCode }}</p>
        </div>
        <div class="action-buttons">
          <el-button type="danger" size="small" @click="stopRental(rental)">停止租用</el-button>
          <el-button type="primary" size="small" :disabled="!canExtend(rental)" @click="extendRental(rental)">
            延长租号
          </el-button>
          <el-button type="warning" size="small" @click="changeGame(rental)">更换游戏</el-button>
        </div>
      </div>
      <div class="empty-text" v-if="rentals.length === 0  && !loading">暂无租用中的游戏账号</div>
    </div>

    <!-- 延长租用对话框 -->
    <el-dialog title="延长租用时间" :visible.sync="extendDialogVisible" width="30%">
      <div style="text-align: center;">
        <p>将为您延长24小时的租用时间</p>
        <p class="time-info">延长后到期时间: {{ formatDate(calculateNewEndTime()) }}</p>
      </div>
      <span slot="footer">
        <el-button @click="extendDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmExtend">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  <script src="../js/axios-0.18.0.js"></script>
  <script src="../js/top.js"></script>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          rentals: [],
          loading: false,
          extendDialogVisible: false,
          extendForm: {
            id: null
          },
          currentRental: null,
          timer: null,
          currentTime: new Date()
        }
      },
      directives: {
        copy: {
          bind(el, binding) {
            el.addEventListener('click', async () => {
              try {
                await navigator.clipboard.writeText(binding.value);
                Vue.prototype.$message.success('验证码已复制到剪贴板' + binding.value);
              } catch (err) {
                console.error('Failed to copy verification code: ', err);
                Vue.prototype.$message.error('复制验证码失败');
              }
            });
          }
        }
      },
      computed: {
        remainingTimesList() {
          const times = {};
          this.rentals.forEach(rental => {
            if (rental.endTime) {
              const end = new Date(rental.endTime);
              const diff = end - this.currentTime;

              if (diff <= 0) {
                times[rental.id] = '已过期';
              } else {
                const hours = Math.floor(diff / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((diff % (1000 * 60)) / 1000);

                const formatNumber = (num) => String(num).padStart(2, '0');
                times[rental.id] = `${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(seconds)}`;
              }
            }
          });
          return times;
        }
      },
      created() {
        this.getCurrentRentals();
      },
      mounted() {
        this.startTimer();
      },
      beforeDestroy() {
        this.stopTimer();
      },
      methods: {
        copyToClipboard(text) {
          if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(() => {
              this.$message.success("内容已复制到剪贴板："+text);
            }).catch(err => {
              this.$message.error("复制失败");
            });
          } else {
            // 对于不支持 Clipboard API 的浏览器，回退方案
            const textArea = document.createElement("textarea");
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            try {
              document.execCommand('copy');
              alert('内容已复制到剪贴板');
            } catch (err) {
              console.error('无法复制文本: ', err);
            } finally {
              document.body.removeChild(textArea);
            }
          }
        },
        startTimer() {
          if (this.timer) {
            clearInterval(this.timer);
          }
          this.timer = setInterval(() => {
            this.currentTime = new Date();
          }, 1000);
        },

        stopTimer() {
          if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
          }
        },

        calculateRemainingTime(endTime) {
          if (!endTime) return '未知';
          const rental = this.rentals.find(r => r.endTime === endTime);
          if (!rental) return '计算中...';
          return this.remainingTimesList[rental.id] || '计算中...';
        },

        async getCurrentRentals() {
          this.loading = true;
          try {
            const response = await fetch('/com/rentals/page?pageNo=1&pageSize=10&status=1');
            if (response.ok) {
              const data = await response.json();
              this.rentals = data.records;
            }
          } catch (error) {
            this.$message.error('获取租用信息失败');
          } finally {
            this.loading = false;
          }
        },

        formatDate(date) {
          if (!date) return '';
          const d = new Date(date);
          const formatNumber = (num) => String(num).padStart(2, '0');

          return `${d.getFullYear()}-${formatNumber(d.getMonth() + 1)}-${formatNumber(d.getDate())} ${formatNumber(d.getHours())}:${formatNumber(d.getMinutes())}:${formatNumber(d.getSeconds())}`;
        },
        async getVerifi(rental) {
          try {


            // 发送请求
            const response = await axios.get("/com/rentals/getVerifi/" + rental.gameAccountId + "/" + rental.id);
            if (response.data.success) {
              this.$message.success(response.data.msg);
              // 更新对应rental的验证码
              this.$set(rental, 'verificationCode', response.data.data);
              return;
            }
            this.$message.error(response.data.msg);
          } catch (error) {
            if (error.response && error.response.status === 403) {
              this.$message.error("无操作权限");
            } else {
              console.error('Error:', error);
              this.$message.error('获取验证码失败');
            }
          }


        },
        stopRental(rental) {
          this.$confirm('确定要停止租用该游戏账号吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const res = await axios.post(`com/rentals/stop?id=${rental.id}`)
            const { code, msg } = res.data
            if (code != 200) {
              this.$message({
                type: 'error',
                message: msg
              })
              return
            }
            this.$message({
              type: 'success',
              message: '停止租用成功'
            })
            this.getCurrentRentals();
          }).catch(() => { });
        },

        canExtend(rental) {
          if (!rental.endTime) return false;

          const now = new Date();
          const end = new Date(rental.endTime);
          const diff = end - now;

          if (diff <= 0) return false;

          const lastExtendTime = rental.lastExtendTime ? new Date(rental.lastExtendTime) : null;
          if (lastExtendTime) {
            const hoursSinceLastExtend = (now - lastExtendTime) / (1000 * 60 * 60);
            if (hoursSinceLastExtend < 24) return false;
          }

          return true;
        },

        getExtendButtonTitle(rental) {
          if (!rental.endTime) return '无法延长租用';
          if (new Date(rental.endTime) - new Date() <= 0) return '租用已过期';

          const lastExtendTime = rental.lastExtendTime ? new Date(rental.lastExtendTime) : null;
          if (lastExtendTime) {
            const hoursSinceLastExtend = (new Date() - lastExtendTime) / (1000 * 60 * 60);
            if (hoursSinceLastExtend < 24) {
              const remainingHours = Math.ceil(24 - hoursSinceLastExtend);
              return `${remainingHours}小时后可再次延长`;
            }
          }

          return '点击延长24小时';
        },

        calculateNewEndTime() {
          if (!this.currentRental) return null;
          const currentEnd = new Date(this.currentRental.endTime);
          return new Date(currentEnd.getTime() + 24 * 60 * 60 * 1000);
        },

        extendRental(rental) {
          this.currentRental = rental;
          this.extendForm = {
            id: rental.id
          };
          this.extendDialogVisible = true;
        },

        async confirmExtend() {
          try {
            const response = await fetch('/com/rentals/extend', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(this.extendForm)
            });

            if (response.ok) {
              const result = await response.json();
              if (result.code === 200) {
                this.$message.success('延长租用成功');
                this.extendDialogVisible = false;
                this.getCurrentRentals();
              } else {
                this.$message.error(result.msg || '延长租用失败');
              }
            }
          } catch (error) {
            console.error('Error:', error);
            this.$message.error('操作失败，请重试');
          }
        },

        isNearExpiration(endTime) {
          if (!endTime) return false;
          const end = new Date(endTime);
          const now = new Date();
          const diff = end - now;

          return diff > 0 && diff < 3600000;
        },

        async changeGame(rental) {
          try {
            await this.$confirm('确定要更换游戏吗？当前游戏账号将被释放', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });

            const response = await fetch(`/com/rentals/stop?id=${rental.id}`, {
              method: 'POST'
            });

            if (response.ok) {
              const result = await response.json();
              if (result.code === 200) {
                this.$message.success('账号已释放，正在跳转到游戏列表...');
                setTimeout(() => {
                  window.location.href = '/index.html';
                }, 1500);
              } else {
                this.$message.error(result.msg || '操作失败');
              }
            }
          } catch (error) {
            if (error !== 'cancel') {
              console.error('Error:', error);
              this.$message.error('操作失败，请重试');
            }
          }
        }
      }
    });
  </script>
</body>

</html>